Zip Support in std.zip

D has support for the zip compression format in std.zip. This example demonstrates its use. You'll need an archive called "test.zip". You can download a version I've used: [ test.zip ]

This page has been superceded by a wiki version of this example: ZipExample



/*



Posted by Walter, walter@digitalmars.com at

news://news.digitalmars.com/D



Subject: Re: zip.d

Date: Mon, 15 Dec 2003 20:29:10 -0800

Organization: Digital Mars

Lines: 85



*/





import std.file;

import std.date;

import std.zip;

import std.zlib;



int main(char[][] args)

{

    byte[] buffer;

    std.zip.ZipArchive zr;

    char[] zipname;

    ubyte[] data;



    testzlib();

    if (args.length > 1) zipname = args[1];

    else zipname = "test.zip";

    buffer = cast(byte[])std.file.read(zipname);

    zr = new std.zip.ZipArchive(cast(void[])buffer);

    printf("comment = '%.*s'\n", zr.comment);

    zr.print();



    foreach (ArchiveMember de; zr.directory)

    {

         de.print();

         printf("date = '%.*s'\n", std.date.toString(std.date.toDtime(de.time)));

        

         arrayPrint(de.compressedData);

        

         data = zr.expand(de);

         printf("data = '%.*s'\n", data);

    }



    printf("**Success**\n");



    zr = new std.zip.ZipArchive();

    ArchiveMember am = new ArchiveMember();

    am.compressionMethod = 8;

    am.name = "foo.bar";

    //am.extra = cast(ubyte[])"ExTrA";

    am.expandedData = cast(ubyte[])"We all live in a yellow submarine, a yellow submarine";

    am.expandedSize = am.expandedData.length;

    zr.addMember(am);

    void[] data2 = zr.build();

    std.file.write("foo.zip", cast(byte[])data2);



    return 0;

}



void arrayPrint(ubyte[] array)

{

    //printf("array %p,%d\n", (void*)array, array.length);

    for (int i = 0; i < array.length; i++)

    {

        printf("%02x ", array[i]);

        if (((i + 1) & 15) == 0)

         printf("\n");

    }

    printf("\n\n");

}



void testzlib()

{

    ubyte[] src = cast(ubyte[])

"the quick brown fox jumps over the lazy dog\r

the quick brown fox jumps over the lazy dog\r

";

    ubyte[] dst;



    arrayPrint(src);

    dst = cast(ubyte[])std.zlib.compress(cast(void[])src);

    arrayPrint(dst);

    src = cast(ubyte[])std.zlib.uncompress(cast(void[])dst);

    arrayPrint(src);

}